package by.bsu.rfe.belianko.euniversity.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;


/**
 * Set UTF-8 encoding
 * 
 * @author Vitali_Belianko
 * 
 */

public class FormEncodingSetterFilter implements Filter {

	private static final String DO_FILTER = "Do filter";
	private static final String FILTERABLE_CONTENT_TYPE = "application/x-www-form-urlencoded";
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final String ENCODING_INIT_PARAM_NAME = "encoding";
	private static final Logger LOGGER = Logger.getLogger(FormEncodingSetterFilter.class);

	private String encoding;

	public void destroy() {
	}

	/**
	 * Sets the encoding of the request and response.
	 * 
	 * @param request
	 *            - ServletRequest
	 * @param response
	 *            - ServletResponse
	 * @param chain
	 *            - FilterChain
	 * @throws ServletException
	 * 
	 * @throws IOException
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException,
			IOException {

		LOGGER.debug(DO_FILTER);

		String contentType = req.getContentType();

		if (contentType != null && contentType.startsWith(FILTERABLE_CONTENT_TYPE))
			req.setCharacterEncoding(encoding);
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig config) throws ServletException {
		encoding = config.getInitParameter(ENCODING_INIT_PARAM_NAME);
		if (encoding == null)
			encoding = ENCODING_DEFAULT;
	}
}
